package cn.appsys.controller;

import cn.appsys.pojo.BackendUser;
import cn.appsys.service.BackendUser.BackendUserService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Log4j
@Controller
@RequestMapping("/backuser")
public class BackendUserController {
    @Autowired
    private BackendUserService backendUserService;

    @PostMapping("/login")
    public String login(HttpServletRequest request, HttpSession session, @RequestParam String userCode, @RequestParam String userPassword){
        log.debug("用户登录");
        BackendUser user = this.backendUserService.getLoginUser(userCode, userPassword);
        if (user != null) {
            if (user.getUserPassword().equals(userPassword)) {
                session.setAttribute("userSession", user);
                return "houtaiindex";
            } else {
                request.setAttribute("message","密码错误");
                return "houtailogin";
            }
        } else {
            request.setAttribute("message","账号不存在");
            return "houtailogin";
        }
    }
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute("userSession") == null) {
            return "redirect:/backuser/toLogin";
        } else {
            log.debug("跳转到首页");
            return "houtaiindex";
        }
    }
    @RequestMapping("/toLogin")
    public String login() {
        log.debug("跳转到后台登录页面");
        return "houtailogin";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session, HttpServletRequest request) {
        log.debug("用户注销");
        request.getSession().invalidate();
        return "index";
    }
}
